package com.zz.study.sharding.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * spring线程池
 */
@Configuration
@Slf4j
public class ExecutorConfig {



    @Bean(name = "shipTrackQueryExecutor")
    public ThreadPoolTaskExecutor shipTrackQueryExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(8);
        //配置最大线程数
        executor.setMaxPoolSize(30);
        //配置队列大小
        executor.setQueueCapacity(1000);
        executor.setKeepAliveSeconds(1);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("船舶轨迹线程-");

        executor.setRejectedExecutionHandler((Runnable r, ThreadPoolExecutor exe) -> {
            log.error("船舶轨迹线程任务被拒绝");
        });
        //执行初始化
        executor.initialize();
        return executor;
    }


    /**
     * 这个策略就是忽略缓冲队列限制，继续往里边塞
     */
    public RejectedExecutionHandler rejectedExecutionHandler() {
        return (r, executor) -> {
            try {
                executor.getQueue().put(r);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
    }


}
